package com.lftea.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.lftea.dao.ITeaDAO;
import com.lftea.po.Tea;

@Repository("teaDAOImpl")
public class TeaDAOImpl implements ITeaDAO {

	@Resource(name = "jdbcTemplate")
	private JdbcTemplate jdbcTemplate;

	public List<Tea> findAll() {
		String sql = "select * from Tea";
		return jdbcTemplate.query(sql, new TeaMapper());
	}

	public Tea findById(long teaId) {
		String sql = "select * from Tea where Tea_ID=?";
		return (Tea) jdbcTemplate.queryForObject(sql, new Object[] { teaId },
				new TeaMapper());
	}

	public void remove(Tea tea) {
		long teaId = tea.getId();
		String sql = "delete Tea where Tea_ID=?";
		jdbcTemplate.update(sql, new Object[] { teaId });
	}

	public void save(Tea tea) {
		long teaId = tea.getId();
		String name = tea.getName();
		String sql = "select count(*) from Tea where Tea_ID=?";
		int result = jdbcTemplate.queryForInt(sql, new Object[] { teaId });
		if (result > 0) {
			sql = "update Tea(Tea_ID, name) values(?,?)";
		} else {
			sql = "insert into Tea(name) values(?)";
		}
		Object[] params = new Object[] { name };
		jdbcTemplate.update(sql, params);
	}

	/**
	 * 定义一个静态的内部类TeaMapper,方便在DAO的方法中被共享
	 */
	private static final class TeaMapper implements RowMapper<Tea> {
		public Tea mapRow(ResultSet rs, int rowNum) throws SQLException {
			Tea tea = new Tea();
			tea.setId(rs.getLong("id"));
			tea.setName(rs.getString("name"));
			return tea;
		}
	}

}
